package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.entity.embeddable.GoodsMatcherRule
import com.zxy.supplier_system.server.entity.embeddable.GoodsMatcherRuleRequestStruct
import com.zxy.supplier_system.server.repository.GoodsBrandRepository
import com.zxy.supplier_system.server.repository.GoodsBrandTagRepository
import com.zxy.supplier_system.server.repository.GoodsCategoryRepository
import com.zxy.supplier_system.server.repository.GoodsRepository
import com.zxy.supplier_system.server.utils.orElse404
import org.springframework.stereotype.Service

@Service
class GoodsMatcherRuleService(
    private val goodsBrandRepository: GoodsBrandRepository,
    private val goodsCategoryRepository: GoodsCategoryRepository,
    private val goodsBrandTagRepository: GoodsBrandTagRepository,
    private val goodsRepository: GoodsRepository,
    private val systemServiceService: SystemServiceService,
) {

    fun configureByRequest(goodsMatcherRule: GoodsMatcherRule,request: GoodsMatcherRuleRequestStruct){
        val systemService = systemServiceService.getCurrentSystemService()
        goodsMatcherRule.includedBrands = request.includedBrandIds.map {
            goodsBrandRepository.findByIdAndSystemService(it, systemService)
                .orElse404("Goods brand not found")
        }.toMutableList()
        goodsMatcherRule.includedCategories = request.includedCategoryIds.map {
            goodsCategoryRepository.findByIdAndSystemService(it, systemService).orElse404("Goods category not found")
        }.toMutableList()
        goodsMatcherRule.includedBrandTags = request.includedBrandTagIds.map {
            goodsBrandTagRepository.findByIdAndSystemService(it,systemService).orElse404()
        }.toMutableList()
        goodsMatcherRule.includedGoodsList = request.includedGoodsIds.map { goodsId ->
            goodsRepository.findByIdAndSystemServiceAndDisableIsFalse(goodsId, systemService).orElse404()
        }.toMutableList()
    }
}